<?php
class Core_Model_Cookie {
	
	const CONFIG_COOKIE_LIFETIME = 'web/cookie/lifetime';

	protected $_lifetime = null;

	protected function _getRequest() {
		return Mag::getRequest();
	}

	protected function _getResponse() {
		return Mag::getResponse();
	}

	public function getDomain() {
		return $this->_getRequest()->getServer('SERVER_NAME');
	}

	public function getPath() {
		return $this->_getRequest()->getBasePath();
	}

	public function getLifetime() {
		if (is_null($this->_lifetime)) {
			$this->_lifetime = Mag::getConfig()->get(self::CONFIG_COOKIE_LIFETIME);
		}
		
		return $this->_lifetime;
	}

	public function setLifetime($value) {
		$this->_lifetime = (int)$value;
		return $this;
	}

	public function isSecure() {
		return $this->_getRequest()->isSecure();
	}

	/**
	 * Set cookie
	 *
	 * @param string $name The cookie name
	 * @param string $value The cookie value
	 * @param int $period Lifetime period
	 * @param string $path
	 * @param string $domain
	 * @param int|bool $secure
	 * @return Core_Model_Cookie
	 */
	public function set($name, $value, $period = null, $path = null, $domain = null, $secure = null) {
		if (!$this->_getResponse()->canSendHeaders()) {
			return $this;
		}
		
		if ($period===null) {
			$period = $this->getLifetime();
		}
		
		$expire = ($period === 0) ? 0 : time() + $period;

		if ($path===null) {
			$path = $this->getPath();
		}
		
		if ($domain===null) {
			$domain = $this->getDomain();
		}
		
		if ($secure===null) {
			$secure = $this->isSecure();
		}
		
		setcookie($name, $value, $expire, $path, $domain, $secure);

		return $this;
	}

	public function get($name = null) {
		if (null === $name) {
			return $_COOKIE;
		}

		return (isset($_COOKIE[$name])) ? $_COOKIE[$name] : null;
	}

	public function delete($name, $path = null, $domain = null, $secure = null) {
		$this->set($name, null, 0, $path, $domain, $secure);
	}
	
}